import Vue from 'vue'
import Router from 'vue-router';
import store from '../store'
import routes from './routes'
Vue.use(Router)
const router = new Router({
  routes: routes
})
// 路由拦截
if (window.localStorage.getItem('token')) {
  store.commit("LOGIN", window.localStorage.getItem('token'))
}

if (window.localStorage.getItem('userInfo')) {
  store.commit("SAVEUSERINFO", JSON.parse(window.localStorage.getItem('userInfo')))
}

if (window.localStorage.getItem('navList')) {
    store.commit("NAVLIST", JSON.parse(window.localStorage.getItem('navList')))
  }
router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
      if (localStorage.getItem('token') ){  // 通过vuex state获取当前的token是否存在
          next();
      }
      else {
          next({
              path: '/login',
              query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
          })
      }
  }
  else {
      next();
  }
})


export default router;
